package com.ruoyi.common.alipay;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.ruoyi.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝API
 */
public class AlipayApi {

    private static final Logger log = LoggerFactory.getLogger(AlipayApi.class);

    private static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLIbXol/OL1/tGhyBCDxzJyrJwlAjRBp/J9ycqEySwVvJkkiXlpf7Flbz3DpApJeyB25FcELqQjRYTpSVpOtj8Dgkrx37PfOKYskcNbKuMzL1QBPvBvPgz3l4KbvCdPI8HQGKEytymh7xFlC5iwtrGyTacdECyTi+ptqH5zcga9aOo8Qt3tXEyJlumJji0zmv8uizawPsytljlEq1gIUeawt+/GoKVuxxFt7i6qyjHqhLrkkm3nwLOK7Egd3Ut1QzWmsv8guNlp7j9XuJOrjsnwL1p6NdC2f+wtD4yUsFcwMU9zGybcOk1OlgEniRvvxAVaeYly+0EFOPbWMP/Rar5AgMBAAECggEAB0JPI966P1cajayqhHHRz4xE0C0aG44nC6qfZauFdh/FTb7DR++kqR7uv81vbWkDiKh2C1o1sJC6Jz2Rlq8Zrfg6b6wTZgrKdjZ4v4wQnVl7sm5bKNM982yQ48KPKq9NVS8B1kkBlZnoKnxfI/xeoRfzsaed4EFXBrOWGj02V3A7epg/HxcG7QJVcWgQLH0Y/Rwtk46jc3kT4mTpPstQ6qM6pmoRuXqTPTA6Jw4NOqhKAnkQwMyxqJWw4uOb6vk/gSNvXWET7+iyZxZ8RWWrea5tUdmlGkIJgj5OaivOiQZllOSyOBukuQgIVE31Wcq9NvbvgjOrpv6hO1MB8/xoWQKBgQDkeLn3JCrpRHbsrz6AUUC/mKlQuWQ8qXYTPgmML74wAt3q8zRFqQKb56lBVGxeSAXBlwpTPw7iDlFP6w7gk0tbM+ca42VU22ko9C9Jl4REjNQUVD2GJz9pHeEygwhzGCi9LnKLVrbKmQAkPDOVl88aSkveB+fB1jipTAPE3DR14wKBgQDjm14GMFPgBug5borapr+TOi68PcJKcEVe2eLpQWC4EB4X0Glkiy9ZsrgvVZusCIxqY0eONKI5GD7IVQ3EMslCUUYcIZfWk1tizkfu3P21F1P06g8e1i2GJYlMx8BIDkZr06NuoB+verJK610Km5bfhuR72/V0j8UH2Ira9OZScwKBgHU7bVDfAhXHx64TDeMRzkOBtf9x4XkvCyM8hfGk3dYM4ooYWQ4Vdv1AlZysER8fnbSEKAwnIx/jcN2tI2kgq14U99TYMbqlCwS0pz7/vCLgkEIOJ7Oal/L8Hf2pNsC3+M958dSFni2+7E+rhFySFPbMgLlhHQ5dOZ3FH3n39AM5AoGBALXI5ly9BpB8E8ejAWXHHmVBaAhSrzXy24T5MyEnZU89GDve6f4yqDvU4QR1NGM/ZJ6n8oOiiBpfwe0Q+XDFOzcrYHqhXfs0MB4HMS6W9E9JdXW75x2y5CMrIbDgLTOfqyD9pJ97ZjMqJPJvbx1EzUh0HVLLiAxzs2Mj0Ss1xCr/AoGAFF7vRtY3wcEdoiHDu5mTcDyXEY1o4b7OUyDjIpc4lbB3OX8FFxf202GoYbZ5yBv1xTXHTqQpb2CFji4DQAM4ks+jgn8YgRQBOiAbPMfubB8V0fD7xCEuOOS/oXbdrRWV8X29Cf5QT6tNUjf1M98p+kNA6J4v20F1Ro9WK67Y3NM=";
    private static String serverUrl = "https://openapi.alipay.com/gateway.do";
    private static String appId = "2021004126653536";
    //    private static String certPath = "H:\\workSpace\\hankai\\达疆汇\\支付宝证书相关\\appCertPublicKey_2021004126653536.crt";
//    private static String alipayPubCertPath = "H:\\workSpace\\hankai\\达疆汇\\支付宝证书相关\\alipayCertPublicKey_RSA2.crt";
//    private static String rootCertPath = "H:\\workSpace\\hankai\\达疆汇\\支付宝证书相关\\alipayRootCert.crt";
    private static String certPath = "/www/wwwroot/comment_test/alipayCert/appCertPublicKey_2021004126653536.crt";
    private static String alipayPubCertPath = "/www/wwwroot/comment_test/alipayCert/alipayCertPublicKey_RSA2.crt";
    private static String rootCertPath = "/www/wwwroot/comment_test/alipayCert/alipayRootCert.crt";

    /**
     * 单笔转账到支付宝账户
     * 提现到客户支付宝账户
     *
     * @param phone          客户支付宝手机号
     * @param name           客户支付宝实名姓名
     * @param withdrawAmount 客户提现金额
     * @return
     * @throws Exception
     */
    public static Map<String, Object> transferToPerson(String phone, String name, BigDecimal withdrawAmount) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        CertAlipayRequest alipayConfig = new CertAlipayRequest();
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(appId);
        alipayConfig.setCharset("UTF8");
        alipayConfig.setSignType("RSA2");
        alipayConfig.setEncryptor("");
        alipayConfig.setFormat("json");
        alipayConfig.setCertPath(certPath);
        alipayConfig.setAlipayPublicCertPath(alipayPubCertPath);
        alipayConfig.setRootCertPath(rootCertPath);
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        String bizNo = "O" + DatePattern.PURE_DATETIME_FORMAT.format(new Date()) + RandomUtil.randomString(4);
        resMap.put("outBizNo", bizNo);
        model.setOutBizNo(bizNo);
        model.setRemark("单笔转账到用户");
        model.setBusinessParams("{\"payer_show_name_use_alias\":\"false\"}");
        model.setBizScene("DIRECT_TRANSFER");
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity(phone);
        resMap.put("phone", phone);
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        payeeInfo.setName(name);
        resMap.put("name", name);
        model.setPayeeInfo(payeeInfo);
        model.setTransAmount(withdrawAmount.toPlainString());
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
        model.setOrderTitle("用户提现");
        request.setBizModel(model);
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        log.info("支付宝提现，返回参数为：{}", response.getBody());
        if (response.isSuccess()) {
            resMap.put("orderId", response.getOrderId());
            resMap.put("payFundOrderId", response.getPayFundOrderId());
            resMap.put("settleSerialNo", response.getSettleSerialNo());
            resMap.put("transDate", response.getTransDate());
            return resMap;
        } else {
            JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_fund_trans_uni_transfer_response");
            String failMsg = jsonObject.getString("sub_msg");
            throw new ServiceException(failMsg);
        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = transferToPerson("xxxxxxxx", "xxx", new BigDecimal("0.1"));
        for (Map.Entry<String, Object> objectEntry : map.entrySet()) {
            System.out.println(objectEntry.getKey() + "：" + objectEntry.getValue());
        }
    }

}
